package com.kob.botrunningsystem.service.impl.utils;

import org.joor.Reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.UUID;
import java.util.function.Supplier;

@Component
public class Consumer extends Thread{
    private Bot bot;
    private static RestTemplate restTemplate;

    private final static String receiveBotMoveUrl = "http://127.0.0.1:3000/pk/receive/bot/move/";

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        Consumer.restTemplate = restTemplate;
    }
    public void startTimeout(long timeout, Bot bot) {
        this.bot = bot;
        this.start();//每次新开一个线程

        try {
            this.join(timeout); // 最多等待timeout秒，若代码超过时间则中断
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            this.interrupt(); // 中断当前线程
        }
    }

    private String addUid(String code, String uid) { // 在 code 中的 Bot类名后添加uid防止类名称相同
        int k = code.indexOf(" implements java.util.function.Supplier<Integer>"); // 从code中找到字符串第一次出现的下标
        return code.substring(0, k) + uid + code.substring(k); // 在上述字符串前面加上一个uid
    }
    @Override
    public void run() { // 编译代码
        UUID uuid = UUID.randomUUID(); // 每次返回一个不一样的ID
        String uid = uuid.toString().substring(0, 8); // 返回前8位
        Supplier<Integer> botinterface = Reflect.compile( // 可以动态编译botinterface代码
                "com.kob.botrunningsystem.utils.Bot" + uid, // 名称:若名称相同的代码只会编译一次，加上uid是为了保证每次类名不一样
                        addUid(bot.getBotCode(), uid)
                         // 代码
        ).create().get(); // 编译完成后创建一个类并且获取到该类

        File file = new File("input.txt");
        try (PrintWriter fout = new PrintWriter(file)) {
            fout.println(bot.getInput()); // 将文件写入bot
            fout.flush(); // 情况缓存区
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }

        Integer direction = botinterface.get();
        System.out.println("move-direction: " + bot.getUserId() + " " + direction);

        MultiValueMap<String, String> data = new LinkedMultiValueMap<>();
        data.add("user_id", bot.getUserId().toString());
        data.add("direction", direction.toString());
        restTemplate.postForObject(receiveBotMoveUrl, data, String.class);
    }
}
